package net.lh.contactsserver.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import net.lh.contactsserver.Config;
import net.lh.contactsserver.entity.ApkInfo;

@Component
public class ApkInfoUtil {
	
	@Autowired
	private Config config;
	
	private static final String APK_INFO_FILE_NAME = "ApkInfo.json";
	
	private static final Logger logger = LoggerFactory.getLogger(ApkInfoUtil.class);

	public ApkInfo load() {
		ApkInfo info = null;
		
		File file = new File(config.getRootPath(), APK_INFO_FILE_NAME);
		if (!file.exists() || !file.isFile()){
			logger.warn("未找到安装包APK定义文件：{}", file.getAbsolutePath());
			return null;
		}
		
		InputStreamReader isr  = null;
		try {
            String apkInfoStr = FileUtils.readFileToString(file, "UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            info = objectMapper.readValue(apkInfoStr, ApkInfo.class);
		} catch (IOException e) {
			logger.error("读取APK信息时发生异常。", e);
		} finally {
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
				}
			}
		}

		return info;
	}

}
